<template>
  <div class="administer">
    <div class="administerNav">
      <backHeader></backHeader>
    </div>
    <div class="administerCont">
      <div class="role html_pst">
        <div class="searchBoxs">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="角色名称：">
              <el-input v-model="request.roleChNameLike"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search(1)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="roleControl">
          <ul style="text-align:right">
            <li @click="showAddForm()">
              <i class="el-icon-circle-plus-outline"></i>添加角色
            </li>
          </ul>
          <el-table :data="tableData" border style="width: 100%"  class="uytv" :max-height="tableHeight">
            <el-table-column type="index" label="序号" width="90"></el-table-column>
            <el-table-column prop="roleChName" label="角色名称" width="180"></el-table-column>
            <el-table-column prop="roleDesc" label="描述"></el-table-column>
            <el-table-column label="操作" >
              <template slot-scope="scope">
                <div class="managementProductList_btn">
                  <el-button @click="showEditView(scope.row)" type="text" size="small">修改</el-button>
                  <el-button @click="showRoleUserView(scope.row.id)" type="text" size="small">角色用户</el-button>
                  <el-button @click="showMenuView(scope.row.id)" type="text" size="small">菜单授权</el-button>
                  <el-button
                    @click="deleteRole(scope.row.id)"
                    type="text"
                    size="small"
                    class="remove"
                  >删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding:10px;text-align:center">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="request.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="request.rows"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 添加/修改 -->
    <el-dialog
      :title="addFormModelTitle"
      :visible.sync="isShowAddForm"
      width="30%"
      custom-class="addRole pop-up"
       v-dialogDrag
    >
      <el-form ref="form" label-width="80px">
        <el-form-item label="角色名称" :rules="[{ required: true, trigger: 'blur' }]">
          <el-input v-model="form.roleChName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="角色类型">
                  <el-select v-model="addRole.type">
                    <el-option label="类型一" value=""></el-option>
                    <el-option label="类型二" value=""></el-option>
                  </el-select>
        </el-form-item>-->
        <el-form-item label="角色描述">
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
        <el-form-item label="角色排序">
          <el-input v-model="form.sortIndex" @input="roleBlur"></el-input>
        </el-form-item>
        <el-form-item class="botm">
          <el-button @click="isShowAddForm=false">取消</el-button>
          <el-button v-if="addFormModelTitle =='添加角色'" @click="createRole()" type="primary">确定</el-button>
          <el-button v-else @click="saveEdit()" type="primary">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 菜单授权 -->
<el-dialog title="菜单授权" :visible.sync="isShowMenu" width="30%" custom-class="addRole pop-up"  v-dialogDrag>
      <div style="height:400px;overflow:auto">
      <el-tree ref="treemenu" default-expand-all node-key="id" :data="treeData" show-checkbox :default-checked-keys="defaultCheckedKeys" @check-change="handleCheckChange"></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowMenu = false">取 消</el-button>
        <el-button @click="updateMenu()" type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色用户 -->
    <el-dialog title="角色用户" :visible.sync="isShowRoleUsers" custom-class="addRole pop-up" class="jsyh" v-dialogDrag>
      <el-form ref="form" :inline="true" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userRoleForm.userNameLike"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getNoContainUserPageJson(1)" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="srte">
        <div class="lt">
          <div class="add">
            <span style="cursor:pointer" @click="addRoleUser()">
              <i class="el-icon-circle-plus-outline"></i>添加
            </span>
          </div>
          <div class="title">可选用户列表</div>
          <el-table
            @selection-change="handleSelectionChange1"
            ref="multipleTable"
            :data="ContainUserList"
            border
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="登录名" prop="loginName"></el-table-column>
            <el-table-column label="昵称" prop="userName"></el-table-column>
          </el-table>
                                                        <el-pagination
                                                        small
                                                        @current-change="ContainUserListCurrentChange"
                                                        :current-page="userRoleForm.page"
                                                        :page-size="userRoleForm.pageSize"
                                                        layout="prev, pager, next"
                                                        :total="ContainUserListTotalCount">
                                                        </el-pagination>
        </div>
        <div class="rt">
          <div class="remor">
            <span style="cursor:pointer" @click="deleteRoleUser()">
              <i class="el-icon-delete"></i>删除
            </span>
          </div>
          <div class="title">已选用户列表</div>
          <el-table
            @selection-change="handleSelectionChange"
            ref="multipleTable"
            :data="NoContainUserList"
            border
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="登录名" prop="loginName"></el-table-column>
            <el-table-column label="昵称" prop="userName"></el-table-column>
          </el-table>
                                                        <el-pagination
                                                        small
                                                        @current-change="NoContainUserListCurrentChange"
                                                        :current-page="NoContainUserListCurrentPage"
                                                        :page-size="10"
                                                        layout="prev, pager, next"
                                                        :total="NoContainUserListTotalCount">
                                                        </el-pagination>
        </div>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="isShowRoleUsers = false">关 闭</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>
<script>
import backHeader from "@/views/common/backHeader.vue";
export default {
  data() {
    return {
      tableHeight:200,
      defaultCheckedKeys:[],
      request: {
        roleChNameLike: "",
        page: 1,
        rows: 20
      },
      isShowAddForm: false,
      addFormModelTitle: "添加角色",
      form: {
        roleChName: "",
        roleDesc: "",
        sortIndex: ""
      },
      tableData: [],
      totalCount: 0,
      treeData: [],
      isShowRoleUsers: false,
      ContainUserList: [],
      NoContainUserList: [],
      authorization: false,
      userRoleFormId: 0,
      NoContainUserListCurrentPage:1,
      userRoleForm: {
        userNameLike: "",
        page: 1,
        rows: 10
      },
      multipleSelection: [],
      multipleSelection1: [],
      isShowMenu: false,
      updateMenuId: 0,
      totalMenuList: [],
      ContainUserListTotalCount:0,
      treeRootId:0,
      NoContainUserListTotalCount:0
    };
  },
  methods: {
    roleBlur(){
      if(!isNaN(this.form.sortIndex)){
          this.request.priceMin = parseInt(this.form.sortIndex)
      }else{
        this.form.sortIndex = ''
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(this.$refs.treemenu)
    },
    initData() {
      this.search(1);
      let self = this
      this.$http.get("/api/users/getCurrentUser", {}, function(res) {
        if (res.success) {
          self.totalMenuList = res.data.permissions;
                var root = 0
                for(var i = 0;i<self.totalMenuList.length;i++){
                  if(self.totalMenuList[i].permPid == 0){
                    self.treeRootId = self.totalMenuList[i].id
                  }
                    if(self.totalMenuList[i].permPid==''){
                        root = self.totalMenuList[i].id
                    }
                }
          self.treeData = self.filterArray(self.totalMenuList, root);
          console.log(self.treeData)
        }
      });
      // this.$http.get("/api/roles/menus/getAllMenuTreeJson", {}, function(res) {
      //   if (res.success) {
      //     self.totalMenuList = res.data;
      //           var root = 0
      //           for(var i = 0;i<self.totalMenuList.length;i++){
      //               if(self.totalMenuList[i].permPid==''){
      //                   root = self.totalMenuList[i].id
      //               }
      //           }
      //     self.treeData = self.filterArray(self.totalMenuList, root);
      //     console.log(self.treeData)
      //   }
      // });
    },
    showAddForm() {
      this.isShowAddForm = true;
      this.addFormModelTitle = "添加角色";
      this.form = {
        roleChName: "",
        roleDesc: "",
        sortIndex: ""
      };
    },
    createRole() {
      if(this.form.roleChName == ''){
        this.$message.error('请输入角色名称！')
        return false;
      }
      let self = this;
      this.$http.postObj("/api/roles/create", this.form, function(res) {
        if (res.success) {
          self.$message({
            message: "添加成功！",
            type: "success"
          });
          self.search(1);
          self.search(1);
          self.isShowAddForm = false;
        }else{
            self.$message.error(res.data)
          }
      });
    },
    search(page) {
      let self = this;
      this.page = page;
      this.$http.postObj("/api/roles/pageJson", this.request, function(res) {
        if (res.success) {
          self.tableData = res.data.rows;
          self.totalCount = res.data.total;
        }
      });
    },
    showEditView(row) {
      this.isShowAddForm = true;
      this.addFormModelTitle = "修改角色";
      this.form = {
        id: row.id,
        roleChName: row.roleChName,
        roleDesc: row.roleDesc,
        sortIndex: row.sortIndex
      };
    },
    saveEdit() {
      if(this.form.roleChName == ''){
        this.$message.error('请输入角色名称！')
        return false;
      }
      let self = this;
      this.$http.putObj("/api/roles/" + this.form.id, this.form, function(res) {
        if (res.success) {
          self.$message({
            message: "修改成功！",
            type: "success"
          });
          self.search(1);
          self.isShowAddForm = false;
        }else{
              self.$message.error(res.data)
            }
      });
    },
    deleteRole(id) {
      let self = this;
      this.$confirm('您确定要删除吗?','提示',{
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
      }).then(()=>{
      this.$http.deletePath("/api/roles/" + id, {}, function(res) {
        if (res.success) {
          self.$message({
            message: "删除成功！",
            type: "success"
          });
          self.search(1);
        }else{
              self.$message.error(res.data)
            }
      });
    }).catch(()=>{});
    },
    showRoleUserView(roleid) {
      this.isShowRoleUsers = true;
      this.userRoleForm.userNameLike = ''
      this.userRoleFormId = roleid;
      this.getContainUser(1);
      this.getNoContainUserPageJson(1);
    },
    getContainUser(page) {
      this.NoContainUserListCurrentPage = page
      //分页获取角色已选用户
      let self = this;
      this.$http.postObj(
        "/api/roles/users/getContainUserPageJson/" + this.userRoleFormId,
        { order: "asc", page: this.NoContainUserListCurrentPage, rows: 10 },
        function(res) {
          if (res.success) {
            self.NoContainUserList = res.data.rows;
            self.NoContainUserListTotalCount = res.data.total;
          }
        }
      );
    },

    getNoContainUserPageJson(page) {
      this.userRoleForm.page = page
      //分页获取当前角色可选用户
      let self = this;
      this.$http.postObj(
        "/api/roles/users/getNoContainUserPageJson/" + this.userRoleFormId,
        this.userRoleForm,
        function(res) {
          if (res.success) {
            self.ContainUserList = res.data.rows;
            self.ContainUserListTotalCount = res.data.total;
          }
        }
      );
    },
    ContainUserListCurrentChange(page){
      this.getNoContainUserPageJson(page)
    },
    NoContainUserListCurrentChange(page){
      this.getContainUser(page)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    addRoleUser() {
      //角色下添加用户
      if (this.multipleSelection1.length == 0) {
        this.$message.error("请至少选择一项");
        return false;
      }

      var userIds = "";
      for (var i = 0; i < this.multipleSelection1.length; i++) {
        userIds += this.multipleSelection1[i].id + ",";
      }
      let self = this;
      userIds = userIds.substring(0, userIds.length - 1);
      this.$http.postQuery(
        "/api/roles/users/addRoleUser/" + this.userRoleFormId,
        {userIds:userIds},
        function(res) {
          console.log(res);
          if (res.success) {
            self.$message({
              message: "添加成功！",
              type: "success"
            });
      self.getContainUser(1);
      self.getNoContainUserPageJson(1);
          }else{
              self.$message.error(res.data)
            }
        });
    },
    deleteRoleUser() {
      //删除角色下已选用户
      if (this.multipleSelection.length == 0) {
        this.$message.error("请至少选择一项");
        return false;
      }
      var userIds = "";
      for (var i = 0; i < this.multipleSelection.length; i++) {
        userIds += this.multipleSelection[i].id + ",";
      }
      let self = this;
      userIds = userIds.substring(0, userIds.length - 1);
      this.$http.deletePath(
        "/api/roles/users/" + this.userRoleFormId,
        {userIds:userIds},
        function(res) {
          self.getNoContainUserPageJson(1);
          if (res.success) {
            self.$message({
              message: "删除成功！",
              type: "success"
            });
      self.getContainUser(1);
      self.getNoContainUserPageJson(1);
          }else{
              self.$message.error(res.data)
            }
        }
      );
    },
    handleCurrentChange(page) {
      this.search(page);
    },
    handleSizeChange(pageSize) {
      this.request.rows = pageSize;
      this.search(1);
    },
    showMenuView(id) {
      this.isShowMenu = true;
      //获得菜单式树
      setTimeout(this.getCurrentMenu,100,id);
      
    },
    getCurrentMenu(id){
      let self = this
      console.log(id)
      self.defaultCheckedKeys = []
      console.log(this.$refs)
      self.$refs.treemenu.setCheckedKeys(self.defaultCheckedKeys); 
      
      //获得该权限已经选择的菜单
      this.$http.get("/api/roles/menus/getRoleMenuTreeJson/" + id, {}, function(
        res
      ) {
        var tempList = []
        // console.log(res.data.length)
        for(var i = 0;i<res.data.length;i++){
          // console.log(res.data[i])
          // console.log(res.data[i].permId)
          // var flag = false
          var woquId = res.data[i].permId
          tempList.push(woquId)
          // for(var j = 0;j<this.treeData.length;j++){
          //   if(woquId == this.treeData[j].id){
          //     flag = true
          //   }
          // }
          // self.defaultCheckedKeys.push(woquId)
          // console.log(self.defaultCheckedKeys)
        }
        //去掉二级菜单id
        for(var i = 0;i<tempList.length;i++){
          for(var j = 0;j<self.treeData.length;j++){
          console.log(tempList[i])
            if(tempList[i] == self.treeData[j].id){
              tempList.splice(i,1)
            }
          }
        }
        console.log(tempList)
        self.$refs.treemenu.setCheckedKeys(tempList); 
      });
      this.updateMenuId = id;
    },
    distinctArray(array){
      //一个新的数组 
      var arrs = []; 
      //遍历当前数组 
      for(var i = 0; i < array.length; i++){ 
          //如果临时数组里没有当前数组的当前值，则把当前值push到新数组里面 
          if (arrs.indexOf(array[i]) == -1){ 
              arrs.push(array[i])
          }; 
      } 
      return arrs; 
    },
    updateMenu() {
      var checkedTree = this.$refs.treemenu.getCheckedNodes();
      console.log(checkedTree)
      var temp = [this.treeRootId];
      if (checkedTree.length == 0) {
        this.$message.error("至少选择一项");
        return false;
      }
      for (var i = 0; i < checkedTree.length; i++) {
        temp.push(checkedTree[i].id);
        temp.push(checkedTree[i].permPid);
      }
      console.log(temp)
      var distinct = this.distinctArray(temp)
      console.log(distinct)
      let self = this
      this.$http.putObj(
        "/api/roles/menus/" + this.updateMenuId,
        distinct,
        function(res) {
          console.log(res);
          if (res.success) {
            self.$message({
              message: "更新成功！",
              type: "success"
            });
            self.isShowMenu = false
          }else{
              self.$message.error(res.data)
            }
        }
      );
    },
    filterArray(data, parent) {
      let vm = this;
      var tree = [];
      var temp;
      for (var i = 0; i < data.length; i++) {
        data[i].label = data[i].permName;
        if (data[i].permPid == parent) {
          var obj = data[i];
          temp = this.filterArray(data, data[i].id);
          if (temp.length > 0) {
            obj.children = temp;
          }
          tree.push(obj);
        }
      }
      return tree;
    }
  },
  created() {
    this.initData();
  },
  components: {
    backHeader
  },
  mounted(){
        this.$nextTick(function () {
            this.tableHeight = window.innerHeight - 280;
            
            // 监听窗口大小变化
            let self = this;
            window.onresize = function() {
                self.tableHeight = window.innerHeight - 280
            }
        })
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" >
.uytv{
  max-height: calc(100% - 170px);
  max-height: -webkit-calc(100% - 170px);
}
.uytv tr td:nth-child(3){
  border-right: 2px solid #d3dde2;
}
.searchBoxs{
  .el-form-item{
    margin-bottom: 0px;
  }
}
.el-dialog__wrapper .el-dialog.addRole {
height: auto;
  max-height: 80vh;
  overflow: auto;
}
.role {
  .searchBoxs {
    .el-form-item {
      .el-form-item__content {
        .el-input {
          width: 300px;
        }
      }
      .el-form-item__label {
        font-size: 14px;
        color: #333;
      }
      .el-button--primary {
        background-color: #5b65a1;
        border-radius: 4px;
        border: none;
      }
    }
  }
}
//弹窗样式
.pop-up {
  .el-menu-item,
  .el-submenu__title {
    height: 36px;
    line-height: 36px;
  }
  .el-menu-item-group__title {
    display: none;
  }
  .el-submenu .el-menu-item {
    padding-left: 60px !important;
  }
  .el-menu {
    border: none;
  }
  .el-dialog__header {
    text-align: center;
    .el-dialog__title {
      font-weight: bold;
    }
    .el-dialog__headerbtn {
      width: 22px;
      height: 22px;
      text-align: center;
      line-height: 24px;
      border-radius: 50%;
      background-color: #5962a3;
      i {
        color: #fff;
      }
    }
  }
  .el-dialog__body {
    padding-top: 10px;
    .el-button--primary {
      background-color: #5962a3;
      border-radius: 3px;
      border: none;
    }
  }
  .botm {
    .el-form-item__content {
      margin-left: 0 !important;
    }
    text-align: center;
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
  .el-dialog__footer {
    text-align: center;
    .el-button--primary {
      background-color: #5962a3;
      border-radius: 3px;
      border: none;
    }
  }
  .srte {
    width: 100%;
    display: inline-block;
    .lt {
      width: 48%;
      float: left;
      margin-right: 4%;
      .add {
        color: #333;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
    .rt {
      width: 48%;
      float: left;
      .remor {
        color: #333;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
    .title {
      border: 1px solid #ebeef5;
      border-bottom: 0;
      padding: 6px;
      background-color: #f2f2f2;
    }
    td,
    th {
      text-align: center;
      font-size: 12px;
      padding: 5px 0;
    }
  }
}
.el-checkbox__inner{
  height: 14px;
}
.el-dialog__wrapper .el-dialog.pop-up{
  height: auto;
  max-height: 80vh;
}
.jsyh{

}
</style>